package com.example.griddemo.adapter;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.griddemo.R;
import com.example.griddemo.viewmodel.Category;

import java.util.ArrayList;
import java.util.List;

public class CategoryTabsAdapter extends RecyclerView.Adapter<CategoryTabsAdapter.ViewHolder> {
    private List<Category> categories;
    private int selectedPosition = 0;
    private OnTabClickListener listener;

    public interface OnTabClickListener {
        void onTabClick(Category category);
    }

    public CategoryTabsAdapter(List<Category> categories) {
        this.categories = categories != null ? categories : new ArrayList<>();
    }

    public void setOnTabClickListener(OnTabClickListener listener) {
        this.listener = listener;
    }

    public void setSelectedPosition(int position) {
        this.selectedPosition = position;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_category_tab, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Category category = categories.get(position);
        boolean isSelected = position == selectedPosition;
        holder.bind(category, isSelected);

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onTabClick(category);
            }
            setSelectedPosition(position);
        });
    }

    @Override
    public int getItemCount() {
        return categories.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;

        ViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_tab_name);
            tvName.setTextColor(Color.BLACK); // 设置导航栏文字为黑色
        }

        void bind(Category category, boolean isSelected) {
            tvName.setText(category.getName());
            tvName.setSelected(isSelected);
            tvName.setTextSize(isSelected ? 16 : 14);
            tvName.setTextColor(isSelected ? Color.BLACK : Color.GRAY);
        }
    }
}